//
//  TMVipCenterController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/7/4.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMVipCenterController.h"
#import "TMUserViewModel.h"
#import "TMVipModel.h"
#import "TMAccountPayView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
@interface TMVipCenterController ()
@property (weak, nonatomic) IBOutlet UIImageView *vipImage;
@property (weak, nonatomic) IBOutlet UIButton *nowVipBtn;
@property (weak, nonatomic) IBOutlet UIButton *nowVipBtn1;
@property (weak, nonatomic) IBOutlet UIButton *nowVipBtn2;
@property (weak, nonatomic) IBOutlet UIView *vipView;
@property (weak, nonatomic) IBOutlet UIView *superVipView;
@property (weak, nonatomic) IBOutlet UIView *godVipView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vipBtnTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *superVipBtnTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *godVipBtnTop;
@property (weak, nonatomic) IBOutlet UILabel *vipLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLimitLabel;
@property (weak, nonatomic) IBOutlet UIButton *automaticRenewalBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vipButtomConst;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *svipButtomConst;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *godvipButtomConst;
@property (nonatomic, strong) TMUserViewModel *viewModel;
@property (nonatomic, strong) NSArray *listArray;

@property (weak, nonatomic) IBOutlet UILabel *vipTitle;
@property (weak, nonatomic) IBOutlet UILabel *vipDiscLavel;
@property (weak, nonatomic) IBOutlet UILabel *supTitle;
@property (weak, nonatomic) IBOutlet UILabel *supDisc;
@property (weak, nonatomic) IBOutlet UILabel *godTitle;
@property (weak, nonatomic) IBOutlet UILabel *godDisc;
@property (nonatomic, assign) NSInteger rank;
@property (nonatomic, strong) TMAccountPayView *accountPayView;
@property (weak, nonatomic) IBOutlet UILabel *uplabel;
@property (weak, nonatomic) IBOutlet UILabel *vipLimitLabel;
@property (weak, nonatomic) IBOutlet UITableViewCell *autoVip;
@property (weak, nonatomic) IBOutlet UILabel *upLabelDate;


@end

@implementation TMVipCenterController
//升级
- (IBAction)busimessUpAction:(UIButton *)sender {
    if (self.rank == 0) {
        self.rank = 1;
    }
//        if (self.rank == 0) {
//            [self openVipAction:self.rank];
//        }else
        if (self.rank == 1) {
            [self openSvipAction:self.rank];
        }
        else if (self.rank == 2) {
            [self openGouvipAction:self.rank];
        }else{
            if (self.rank == 3) {
                return;
            }
        }
}
//开启自动续费
- (IBAction)automaticRenewalAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        [sender setTitle:@"已开启" forState:UIControlStateSelected];
    }else{
        [sender setTitle:@"未开启" forState:UIControlStateNormal];
    }
}
- (NSArray *)listArray{
    if (!_listArray) {
        _listArray = [NSArray array];
    }
    return _listArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"会员中心";
    self.autoVip.hidden = YES;
    self.upLabelDate.text = @"";
    self.tableView.tableFooterView = [UIView new];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:@"ZLAliReturnSucceedPayNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFailed:) name:@"ZLAliReturnFailedPayNotification" object:nil];
    [self displayUIs];
    self.viewModel = [[TMUserViewModel alloc]init];
    [self.viewModel getVipListWithSuccess:^(id respon,id responseObject) {
        self.listArray = responseObject;
        self.rank = [respon integerValue];
        [self displayCellData];
    } AndFiled:^(NSString *error) {
        
    }];
}
- (void)displayUIs{
    self.nowVipBtn.hidden = YES;
    self.nowVipBtn2.hidden = YES;
    self.nowVipBtn1.hidden = YES;
    self.vipView.layer.borderWidth = 1.0f;
    self.vipView.layer.borderColor = [UIColor hx_colorWithHexRGBAString:@"#ECECEC"].CGColor;
    self.superVipView.layer.borderWidth = 1.0f;
    self.superVipView.layer.borderColor = [UIColor hx_colorWithHexRGBAString:@"#EEEEEE"].CGColor;
    
    self.godVipView.layer.borderWidth = 1.0f;
    self.godVipView.layer.borderColor = [UIColor hx_colorWithHexRGBAString:@"#ECECEC"].CGColor;
//    UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(vipOpen:)];
//    [self.vipView addGestureRecognizer:taps];
    UITapGestureRecognizer *taps1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(svipOpen:)];
    [self.superVipView addGestureRecognizer:taps1];
    UITapGestureRecognizer *taps2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(godVipOpen:)];
    [self.godVipView addGestureRecognizer:taps2];
}
- (void)vipOpen:(UITapGestureRecognizer *)tap{
    if (self.rank >1) {
        return;
    }
    self.vipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
    self.superVipView.backgroundColor = [UIColor whiteColor];
    self.godVipView.backgroundColor = [UIColor whiteColor];
    [self displayVip:1 And:NO];
    [self openVipAction:0];
    [self.tableView reloadData];
}
- (void)openVipAction:(NSInteger)nextvip{
    TMVipModel *model1 = self.listArray[nextvip];
    [self.viewModel commitVipOrderWithName:model1.name Success:^(id responseObject) {
        [self reallyToPay:[responseObject[@"money"] floatValue] AndNum:responseObject[@"number"]];
    } AndFiled:^(NSString *error) {
        
    }];
}


- (void)svipOpen:(UITapGestureRecognizer *)tap{
    if (self.rank>2) {
        return;
    }
    self.vipView.backgroundColor = [UIColor whiteColor];;
    self.superVipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
    self.godVipView.backgroundColor = [UIColor whiteColor];
    [self displayVip:2 And:NO];
    [self openSvipAction:1];
    [self.tableView reloadData];
}
- (void)openSvipAction:(NSInteger)next{
    TMVipModel *model2 = self.listArray[next];
    [self.viewModel commitVipOrderWithName:model2.name Success:^(id responseObject) {
        [self reallyToPay:[responseObject[@"money"] floatValue] AndNum:responseObject[@"number"]];
    } AndFiled:^(NSString *error) {
        
    }];
}
- (void)godVipOpen:(UITapGestureRecognizer *)tap{
    if (self.rank >=3) {
        return;
    }
    self.vipView.backgroundColor = [UIColor whiteColor];
    self.superVipView.backgroundColor = [UIColor whiteColor];
    self.godVipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
    [self displayVip:3 And:NO];
    [self openGouvipAction:2];
    [self.tableView reloadData];
}
- (void)openGouvipAction:(NSInteger)next{
    TMVipModel *model3 = self.listArray[next];
    [self.viewModel commitVipOrderWithName:model3.name Success:^(id responseObject) {
        [self reallyToPay:[responseObject[@"money"] floatValue] AndNum:responseObject[@"number"]];
    } AndFiled:^(NSString *error) {
        
    }];
}

- (void)displayCellData{
    if (self.rank == 0 ) {
        self.rank = 1;
    }
    TMVipModel *model1 = self.listArray[0];
    self.vipTitle.text = [NSString stringWithFormat:@"%@:免费",model1.intro];
    self.vipDiscLavel.text = model1.remark;
    if (self.rank > 1) {
        self.vipLimitLabel.text = [NSString stringWithFormat:@"会员有效期:%@", model1.end_time];
        self.vipImage.image = [UIImage imageNamed:@"金卡"];

    }
    TMVipModel *model2 = self.listArray[1];
    self.supTitle.text = [NSString stringWithFormat:@"%@:%ld元/%@",model2.intro,model2.val,model2.expiration_time];
    self.supDisc.text = model2.remark;
    TMVipModel *model3 = self.listArray[2];
    self.godTitle.text = [NSString stringWithFormat:@"%@:%ld元/%@",model3.intro,model3.val,model3.expiration_time];
    self.godDisc.text = model3.remark;
    if (self.rank < 3) {
        TMVipModel *nowmodel = self.listArray[self.rank];
        self.uplabel.text = [NSString stringWithFormat:@"升级为%@",nowmodel.intro];
    }else{
        self.uplabel.text = [NSString stringWithFormat:@"当前为最高等级会员"];
        self.dateLimitLabel.text = [NSString stringWithFormat:@"会员有效期:%@", model1.end_time];
    }
    [self displayVip:self.rank And:NO];
    [self.tableView reloadData];
}
- (void)displayVip:(NSInteger)rank And:(BOOL)isShow{
    if (rank == 0) {
        self.vipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn.hidden = YES;
        self.superVipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn1.hidden = YES;
        self.godVipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn2.hidden = YES;
    }
    if (rank == 1) {
        self.vipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
        self.vipDiscLavel.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
        self.vipTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
        self.supTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.supDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.godDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.godTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.nowVipBtn.hidden = NO;
        self.superVipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn1.hidden = YES;
        self.godVipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn2.hidden = YES;
    }if (rank == 2) {
        
        self.vipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn.hidden = YES;
        self.superVipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
        self.nowVipBtn1.hidden = NO;
        self.vipDiscLavel.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.vipTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.supTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
        self.supDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
        self.godDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.godTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.godVipView.backgroundColor = [UIColor whiteColor];
    }
    if (rank == 3) {
        self.vipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn.hidden = YES;
        self.superVipView.backgroundColor = [UIColor whiteColor];
        self.nowVipBtn1.hidden = YES;
        self.godVipView.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"F5D089"];
        self.nowVipBtn2.hidden = NO;
        self.vipDiscLavel.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.vipTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.supTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.supDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#CCCCCC"];
        self.godDisc.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
        self.godTitle.textColor = [UIColor hx_colorWithHexRGBAString:@"#FFFFFF"];
    }
}

-(TMAccountPayView*)accountPayView{
    if (_accountPayView == nil) {
        _accountPayView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:self options:nil][1];
    }
    return _accountPayView;
}
- (void)paySuccess:(NSNotification *)noti{
    if (self.accountPayView) {
        [self.accountPayView removeFromSuperview];
    }
    [TMProgressHUD showSuccessWithStyleDarkStatus:@"支付成功"];
    [self performSelector:@selector(gotoHome) withObject:nil afterDelay:1];
    //    TMBaseTabbarContriller *rootTabbar = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBaseTabbarContriller"];
    //    rootTabbar.selectedIndex = 0;
    //    [UIApplication sharedApplication].keyWindow.rootViewController = rootTabbar;
}
- (void)gotoHome{
//    TMBaseTabbarContriller *rootTabbar = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBaseTabbarContriller"];
//    rootTabbar.selectedIndex = 0;
//    [UIApplication sharedApplication].keyWindow.rootViewController = rootTabbar;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)payFailed:(NSNotification *)noti{
    [TMProgressHUD showErrorWithStyleDarkStatus:@"支付失败！"];
    if (self.accountPayView) {
        [self.accountPayView removeFromSuperview];
    }
}

- (void)reallyToPay:(float)all AndNum:(NSString*)num{
    _accountPayView = [[NSBundle mainBundle] loadNibNamed:@"TMDiscountDetailView" owner:self options:nil][1];
    _accountPayView.frame = CGRectMake(0, 0, self.navigationController.view.bounds.size.width, self.navigationController.view.bounds.size.height);
    [self.navigationController.view addSubview:_accountPayView];
    _accountPayView.bankLabel.text = [NSString stringWithFormat:@"所需支付:%.02f元",all];
    //__weak typeof(self) weakself = self;
    _accountPayView.block = ^(NSInteger code) {
        //        if (code == 2) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:@(code) forKey:@"type"];
        [param setValue:[TMUserManager deaufatManager].userModel.token forKey:@"token"];
        [param setValue:@([TMUserManager deaufatManager].userModel.uid) forKey:@"uid"];
        [param setValue:num forKey:@"number"];
        [param setValue:@(all) forKey:@"money"];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
        [securityPolicy setAllowInvalidCertificates:YES];
        [manager setSecurityPolicy:securityPolicy];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];//,@"application/json"
        [manager POST:@"http://app.yxp123.com/home/pays/member" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
            if (code == 2) {
                NSString *appScheme = @"yxpyhd";
                [[AlipaySDK defaultService] payOrder:string fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);
                }];
            }else{
                //                    {"appid":"wx9bd061b8f82368af","partnerid":"1510892881","prepayid":"wx0318300949253521f507dddc0713511872","timestamp":"1535970609","noncestr":"RJg2Npdi08AG4Lkf","package":"Sign=WXPay","sign":"E4AF2848592F0661888CE1788CA04E4C"}
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dic objectForKey:@"appid"];
                req.partnerId           = [dic objectForKey:@"partnerid"];
                req.prepayId            = [dic objectForKey:@"prepayid"];
                req.nonceStr            = [dic objectForKey:@"noncestr"];
                req.timeStamp           = [[dic objectForKey:@"timestamp"] intValue];
                req.package             = [dic objectForKey:@"package"];
                req.sign                = [dic objectForKey:@"sign"];
                [WXApi sendReq:req];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error%@", error);
            
        }];
        //        }else{
        //
        //        }
    };
}
- (IBAction)continueOpenAction:(UIButton *)sender {
    
}
//237 80 67
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 237;
    }
    if (indexPath.row == 1) {
        return 80;
    }
    if (indexPath.row == 2) {
        return 67;
    }
    return 0;
}
@end
